package com.test.pattern.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: BoxFactory
 * @description: 工厂类将该类设计为单例(享元工厂角色)
 * @author: Mr du
 * @create: 2024-02-25 21:20
 */
public class BoxFactory {

    private Map<String,AbstractBox> map = new HashMap<>();

    private BoxFactory(){
        AbstractBox iBox = new IBox();
        AbstractBox lBox = new LBox();
        AbstractBox oBox = new OBox();
        map.put("I", iBox);
        map.put("L", lBox);
        map.put("O", oBox);
    }

    /**
     * 定义内部类懒汉式方式
     */
    private static class SingletonHolder{
        private final static BoxFactory INSTANCE = new BoxFactory();
    }

    //提供给外界访问的单例模式
    public static BoxFactory getInstance(){
        return SingletonHolder.INSTANCE;
    }

    public AbstractBox getKey(String key){
        //此处应该有防御性编程
        if (!map.containsKey(key)){
            return null;
        }
        return map.get(key);
    }
}
